<?php
class Db{
    private $host;
    private $root;
    private $pwd;
    private $dbname;
    private $port;
    private $charset;
    public $link;
    public function __construct($parmas)
    {
        $this->init($parmas);
        $this->connect();
    }
    private function init($parmas=array()){
        $this->host=$parmas['host']??'localhost';
        $this->root=$parmas['root']??'root';
        $this->pwd=$parmas['pwd']??'root';
        $this->dbname=$parmas['dbname'];
        $this->port=$parmas['port']??'3306';
        $this->charset=$parmas['charset']??'utf8';
    }
    private function connect(){
        $this->link=@mysqli_connect($this->host,$this->root,$this->pwd,$this->dbname,$this->port);
        if(!$this->link){
            echo "数据库连接失败".mysqli_connect_error();
            exit;
        }
        mysqli_set_charset($this->link,$this->charset);
    }
    //执行增删改查
    public function execute($sql){
        if(!$str=mysqli_query($this->link,$sql)){
            echo "sql语句执行错误".mysqli_error($this->link);
            echo "<br>错误的sql语句是".$sql;
            exit;
        }
        return $str;
    }
    //查
    public function select($sql,$type="num"){
        $result=$this->execute($sql);
        $type=$this->getType($type);
        if((mysqli_num_rows($result))>0){
            // echo $type;
            return mysqli_fetch_all($result,$type);
        }
    }
    //查询返回数组类型
    private function getType($type){
        if($type='asso'){
            $type=MYSQLI_ASSOC;
        }else if($type=='num'){
            $type=MYSQLI_NUM;
        }else{
            $type=MYSQLI_BOTH;
        }
        return $type;
    }
}
// $str=[
//     'host'=>'127.0.0.1',
//     'root'=>'root',
//     'pwd'=>'root',
//     'dbname'=>'db'
// ];
// $DB=new Db($str);
// // $sql="insert into user values('1','zs','10')";
// // var_dump($DB);
// $sql="select * from user where id=1";
// var_dump($DB->execute($sql,'asso'));
?>